﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Portal.Core.DAL;
using System.Text;
using System.IO;

namespace Portal.BO.Editoral.Tag
{
    public static class TagHelper
    {
        public static DataTable GetListGroupTag(string strWhere, int PageSize, int StartRow)
        {
            if (strWhere == null)
                strWhere = "";
            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_GroupTag", new object[] { strWhere, PageSize.ToString(), StartRow.ToString() }
                                                                            , new string[] { "@strWhere", "@PageSize", "@StartIndex" }, true);
            }
            return dt;
        }

        public static int CountGroupTag(string strWhere)
        {
            if (strWhere == null)
                strWhere = "";
            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_GroupTag_Count", new object[] { strWhere}
                                                                                  , new string[] { "@strWhere"}, true);
            }

            return Convert.ToInt32(dt.Rows[0][0]);
        }

        public static DataTable GetListTag(string strWhere, int PageSize, int StartRow, string SortExpression)
        {
            if (strWhere == null)
                strWhere = "";
            if (string.IsNullOrEmpty(SortExpression))
            {
                SortExpression = " tag_id desc ";
            }

            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_Tag", new object[] { strWhere, PageSize.ToString(), StartRow.ToString(), SortExpression }
                                                                            , new string[] { "@strWhere", "@PageSize", "@StartIndex", "@SortExpression" }, true);
            }
            return dt;
        }

        public static int CountTag(string strWhere)
        {
            if (strWhere == null)
                strWhere = "";
            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_Tag_Count", new object[] { strWhere }
                                                                                  , new string[] { "@strWhere" }, true);
            }

            return Convert.ToInt32(dt.Rows[0][0]);
        }

        public static DataTable GetList_NewsIDNotInTag(string strWhere, int PageSize, int StartRow)
        {
            if (strWhere == null)
                strWhere = "";
           
            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_NewsIDNotInTag", new object[] { strWhere, PageSize.ToString(), StartRow.ToString() }
                                                                            , new string[] { "@strWhere", "@PageSize", "@StartIndex" }, true);
            }
            return dt;
        }

        public static int CountNewsIDNotInTag(string strWhere)
        {
            if (strWhere == null)
                strWhere = "";
            DataTable dt = new DataTable();
            using (MainDB objDb = new MainDB())
            {
                dt = (DataTable)objDb.CallStoredProcedure("GetList_NewsIDNotInTag_Count", new object[] { strWhere }
                                                                                  , new string[] { "@strWhere" }, true);
            }

            return Convert.ToInt32(dt.Rows[0][0]);
        }

        public static void InsertGroupTag(string GroupName, string GroupLink, string Cat_ID)
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.CallStoredProcedure("GroupTagInsert", new object[] { GroupName, GroupLink, Cat_ID, 0 }
                                                          , new string[] { "@GroupName", "@GroupLink", "@Cat_ID", "@Status" }, false);
            }
        }

        public static void UpdateGroupTag(int id, string GroupName, string GroupLink, string Cat_ID)
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.CallStoredProcedure("GroupTagUpdate", new object[] {id, GroupName, GroupLink, Cat_ID, 0 }
                                                          , new string[] {"@id", "@GroupName", "@GroupLink", "@Cat_ID", "@Status" }, false);
            }
        }

        public static void DeleteGroupTag(int id) 
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.CallStoredProcedure("GroupTagDelete", new object[] { id}
                                                          , new string[] { "@id" }, false);
            }
        }

        public static DataTable GetGroupTagInfo(int id)
        {
            DataTable dt;
            using (MainDB objDB = new MainDB())
            {
                dt = objDB.StoredProcedures.vc_Execute_Sql( "Select * From GroupTag Where id = " + id );
            }

            return dt;
        }

        public static void InsertTag(string tag_name, string tag_url, string groupid)
        {
            MainDB objDB = new MainDB();
            
            InsertTag(tag_name, tag_url, groupid, objDB);

            objDB.Close();
            objDB.Dispose();
        }

        public static int InsertTag(string tag_name, string tag_url, string groupid, MainDB objDB)
        {
          DataTable dt = (DataTable) objDB.CallStoredProcedure("TagInsert", new object[] { tag_name, 0, "", 0, tag_url, 0, groupid }
                                                          , new string[] { "@tag_name", "@tag_hot", "@cat_id", "@order", "@tag_url", "@Click", "@groupid" }, true);

          int sReturn = -1;
          if (dt.Rows.Count > 0)
          {
              sReturn = Convert.ToInt32(dt.Rows[0][0].ToString());
          }

          return sReturn;
        }



        public static void UpdateTag(int tag_id, string tag_name, string tag_url, string groupid)
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.CallStoredProcedure("TagUpdate", new object[] {tag_id, tag_name, tag_url, groupid }
                                                     , new string[] {"@tag_id", "@tag_name", "@tag_url", "@groupid" }, false);
            }
        }

        public static void DeleteTag(int tag_id)
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.CallStoredProcedure("TagDelete", new object[] { tag_id }
                                                     , new string[] { "@tag_id" }, false);
            }
        }

        public static DataTable GetTagInfo(int tag_id)
        {
            DataTable dt;
            using (MainDB objDB = new MainDB())
            {
                dt = objDB.StoredProcedures.vc_Execute_Sql(" Select * From Tag Where Tag_ID  = " + tag_id);
            }
            return dt;
        }

        public static DataTable SelectNewsByTag(int TagID)
        {
            using (MainDB db = new MainDB())
            {
                return (DataTable)db.CallStoredProcedure("SelectNewsByTagID", new object[] { TagID }
                                                                , new string[] { "@TagID" }, true);
            }
        }

        public static void DeleteNewsTag(string tag_news_id)
        {
            using (MainDB objDB = new MainDB())
            {
                objDB.StoredProcedures.vc_Execute_Sql(" Delete NewsTag Where tag_news_id IN (" + tag_news_id + ")");
            }
        }

        public static void UpdateNewsTag(int TagID, long NewsID, Portal.Core.DAL.MainDB objDB)
        {
            objDB.CallStoredProcedure("UpdateNewsTag", new object[] { TagID, NewsID }, new string[] { "TagID", "NewsID" }, false);
        }

        public static void WriteJS()
        {
            string file = HttpContext.Current.Server.MapPath("~/Scripts/tag/kby.js");
            StringBuilder _Content = new StringBuilder();
            DataTable tblTags = new DataTable();

            using (MainDB objDB = new MainDB())
            {
                tblTags = objDB.StoredProcedures.vc_Execute_Sql(" Select tag_id,tag_name From Tag ");
            }

            try
            {
                if (tblTags != null && tblTags.Rows.Count > 0)
                {
                    DataRow row = null;
                    _Content.Append("var oc1=[");
                    for (int i = 0; i < tblTags.Rows.Count; i++)
                    {
                        row = tblTags.Rows[i];
                        _Content.Append("{i:" + row["tag_id"] + ",m:\"" + row["tag_name"].ToString().Replace("\"", "").Replace("\'", "") + "\",o:\"" + UnicodeUtility.UnicodeToKoDau(row["tag_name"].ToString().Replace("\"", "").Replace("\'", "")) + "\"}");
                        if (i < tblTags.Rows.Count - 1)
                            _Content.Append(",");
                    }
                    _Content.Append("];");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Channelvn.Tag", ex.ToString() + "***" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return;
            }

            using (StreamWriter sw = new StreamWriter(file, false, Encoding.Unicode))
            {
                sw.Write(_Content.ToString());
                sw.Close();
                sw.Dispose();
            }
        }


        public static void GopTag(string tag_name, string tag_url, string groupid, string strOldTag)
        {
            if (strOldTag.Trim() != "")
            {
                MainDB objDB = new MainDB();
                objDB.BeginTransaction();

                try
                {
                    // Lấy danh sách các bài thuộc Tag Cũ
                    DataTable dt;
                    dt = objDB.StoredProcedures.vc_Execute_Sql("select distinct news_id, tag_id, tag_news_id from newstag where newstag.tag_id in (" + strOldTag + ")");



                    // ==== Xóa các Tag Cũ và Insert Tags mới, dùng transaction
                    // Delete bài thuộc Tag Cu
                    objDB.StoredProcedures.vc_Execute_Sql(" Delete NewsTag Where tag_id in (" + strOldTag + ") ");
                    // Delete Tag
                    objDB.StoredProcedures.vc_Execute_Sql(" Delete Tag Where tag_id in (" + strOldTag + ") ");

                    // Insert Tag Moi
                    int newstagid = InsertTag(tag_name, tag_url, groupid, objDB);

                    // Assign NewsID To Tag
                    if (dt.Rows.Count > 0 && newstagid > -1)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            UpdateNewsTag(newstagid, Convert.ToInt64(dt.Rows[i]["news_id"]), objDB);
                        }
                    }

                    objDB.CommitTransaction();

                }
                catch (Exception ex)
                {
                    objDB.RollbackTransaction();
                }
                finally {
                    objDB.Close();
                    objDB.Dispose();
                }
            }
            
        }

        public static void DeleteTagsByNewsID(long NewsID, Portal.Core.DAL.MainDB objDB)
        {
            objDB.CallStoredProcedure("DeleteTagsByNewsID", new object[] { NewsID }, new string[] { "NewsID" }, false); // StoredProcedures.DeleteTagsByNewsID(NewsID);
        }

    }
}
